<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" label-position="left">
			<el-form-item label="角色名称" prop="roleName">
				<el-input v-model="form.roleName" clearable></el-input>
			</el-form-item>
			<el-form-item label="角色别名" prop="roleKey">
				<el-input v-model="form.roleKey" clearable></el-input>
			</el-form-item>
			<el-form-item label="角色类型" prop="roleType">
				<el-select v-model="form.roleType" style="width: 100%">
					<el-option v-for="option in roleTypeList" :key="option.dictValue" :label="option.dictLabel" :value="option.dictValue"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="权限范围">
				<el-select v-model="form.dataScope">
					<el-option
						v-for="item in dataScopeOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="菜单权限" v-show="form.dataScope == 2">

				<el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
				<el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
				<el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
				<el-tree
					class="tree-border"
					:data="menuOptions"
					show-checkbox
					default-expand-all
					ref="menu"
					node-key="id"
					:check-strictly="!form.menuCheckStrictly"
					empty-text="加载中，请稍候"
					:props="defaultProps"
				></el-tree>
			</el-form-item>
			<el-form-item label="是否有效" prop="status">
				<el-switch v-model="form.status" active-value="0" inactive-value="1"></el-switch>
			</el-form-item>
			<el-form-item label="备注" prop="remark">
				<el-input v-model="form.remark" clearable type="textarea"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '新增角色',
					edit: '编辑角色',
					show: '查看角色'
				},
				visible: false,
				isSaveing: false,
				menuExpand: false,
				menuNodeAll: false,
				roleTypeList:[],
				//表单数据
				form: {
					roleId: undefined,
					roleName: undefined,
					roleKey: undefined,
					roleSort: 0,
					status: "0",
					menuIds: [],
					deptIds: [],
					dataScope:"1",
					menuCheckStrictly: true,
					deptCheckStrictly: true,
					remark: undefined
				},
				// 默认标签
				defaultProps: {
					children: "children",
					label: "label"
				},
				// 菜单列表
				menuOptions: [],
				//验证规则
				rules: {
					roleSort: [
						{required: true, message: '请输入排序', trigger: 'change'}
					],
					roleName: [
						{required: true, message: '请输入角色名称'}
					],
					roleKey: [
						{required: true, message: '请输入角色别名'}
					],
					roleType: [
						{required: true, message: '请选择角色类型'}
					]
				},
				// 数据范围选项
				dataScopeOptions: [
					{
						value: "1",
						label: "全部数据权限"
					},
					{
						value: "2",
						label: "自定数据权限"
					},
					{
						value: "3",
						label: "本部门数据权限"
					},
					{
						value: "4",
						label: "本部门及以下数据权限"
					},
					{
						value: "5",
						label: "仅本人数据权限"
					}
				],
			}
		},
		mounted() {
			this.getMenuTreeSelect();
			this.getDict();
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			// 字典获取
			async getDict() {
				this.roleTypeList = await this.Dict.get("sys_role_type");
			},
			//表单提交方法
			submit(){
				this.form.menuIds = this.getMenuAllCheckedKeys();
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						this.isSaveing = true;
						let res = null;
						if (typeof (this.form.roleId) =='undefined'){
							 res = await this.$API.system.role.saveRole.post(this.form);
						}else {
							 res = await this.$API.system.role.updateRole.put(this.form);
						}
						this.isSaveing = false;
						if(res.code == 200){
							this.$emit('success', this.form, this.mode)
							this.visible = false;
							this.$message.success("操作成功")
						}else{
							this.$alert(res.msg, "提示", {type: 'error'})
						}
					}
				})
			},
			//表单注入数据
			async setData(data) {
				Object.assign(this.form, data)
				let res = await this.$API.system.menu.roleMenuTreeselect.get(data.roleId)
				if (res.code == 200){
					let checkedKeys = res.checkedKeys
					checkedKeys.forEach((v) => {
						this.$nextTick(()=>{
							this.$refs.menu.setChecked(v, true ,false);
						})
					})

				}
				//可以和上面一样单个注入，也可以像下面一样直接合并进去
				//Object.assign(this.form, data)
			},
		     // 查询菜单树结构
			async getMenuTreeSelect() {
				let res = await this.$API.system.menu.treeselect.get(null)
				if (res.code == 200){
					this.menuOptions = res.data;
				}
			},
			// 树权限（展开/折叠）
			handleCheckedTreeExpand(value, type) {
				if (type == 'menu') {
					let treeList = this.menuOptions;
					for (let i = 0; i < treeList.length; i++) {
						this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
					}
				} else if (type == 'dept') {
					let treeList = this.deptOptions;
					for (let i = 0; i < treeList.length; i++) {
						this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
					}
				}
			},
			// 树权限（全选/全不选）
			handleCheckedTreeNodeAll(value, type) {
				if (type == 'menu') {
					if (value){
						this.$refs.menu.setCheckedNodes(this.menuOptions)
					}else{
						this.$refs.menu.setCheckedNodes([])
					}
				} else if (type == 'dept') {
					if (value){
						this.$refs.menu.setCheckedNodes(this.menuOptions)
					}else{
						this.$refs.menu.setCheckedNodes([])
					}
				}
			},
			// 树权限（父子联动）
			handleCheckedTreeConnect(value, type) {
				if (type == 'menu') {
					this.form.menuCheckStrictly = value ? true: false;
				} else if (type == 'dept') {
					this.form.deptCheckStrictly = value ? true: false;
				}
			},
			// 所有菜单节点数据
			getMenuAllCheckedKeys() {
				// 目前被选中的菜单节点
				let checkedKeys = this.$refs.menu.getCheckedKeys();
				// 半选中的菜单节点
				let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
				checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
				return checkedKeys;
			}
		}
	}
</script>

<style>
.tree-border {
	width: 100%;
	height: 200px;
	overflow-y: scroll;
	margin-top: 5px;
	border: 1px solid #e5e6e7;
	background: #FFFFFF none;
	border-radius:4px;
}

</style>
